from sys import flags
import scapy
import csv
from scapy.all import *
from scapy.utils import PcapReader
# from nfstream import NFStreamer
import pandas as pd

pd.set_option('display.width', None)

packets = rdpcap("E:/跑代码测试文件夹/ss5_3-4-4.pcap")

i = 0

# 将第一个TCP包的源IP作为上行数据流的发起者（客户端），因为TCP流总是客户端先发起的
j = 0
while(True):
    if packets[j].haslayer("TCP"):
        upsrc = packets[j].payload.src
        downsrc = packets[j].payload.dst
        timestart = packets[j].time
        print(upsrc,'   ',downsrc,'   ',timestart)
        break
    j = j+1

with open('E:/跑代码测试文件夹/test1.csv', mode='a',encoding='utf-8-sig', newline='') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(['serial number', 'timestamp', 'up/down', 'src ip', 'src port', 'dst ip', 'dst port', 'flags', 'payload length'])

for data in packets:
    if data.haslayer("TCP"):
        if data.payload.src == downsrc and data.payload.dst== upsrc:
        # print(data.payload.payload.flags)
#         if 'TCP' in data:
#         #if Raw in data:
        # print(data.time)
            with open('E:/跑代码测试文件夹/test1.csv', mode='a',encoding='utf-8-sig', newline='') as csvfile:
                writer = csv.writer(csvfile)
                writer.writerow([i, data.time-timestart, 'down', data.payload.src, data.payload.sport, data.payload.dst, data.payload.dport, data.payload.payload.flags, len(data["TCP"].payload.original)])
                # print("%5d|"%i,'down|',data.payload.src.ljust(15),':',"%5s"%data.payload.sport,'-->',data.payload.dst.ljust(15),':',"%5s"%data.payload.dport, "%4s"%data.payload.payload.flags ,len(data["TCP"].payload.original))
        elif data.payload.src== upsrc and data.payload.dst== downsrc:
            with open('E:/跑代码测试文件夹/test1.csv', mode='a',encoding='utf-8-sig', newline='') as csvfile:
                writer = csv.writer(csvfile)
                writer.writerow([i, data.time-timestart,'up', data.payload.src, data.payload.sport, data.payload.dst, data.payload.dport, data.payload.payload.flags, len(data["TCP"].payload.original)])
                # print("%5d|"%i,' up |',data.payload.src.ljust(15),':',"%5s"%data.payload.sport,'-->',data.payload.dst.ljust(15),':',"%5s"%data.payload.dport, "%4s"%data.payload.payload.flags ,len(data["TCP"].payload.original))
    i = i + 1